/*
 * Created on Jun 23, 2004
 */
package com.scalar.chiptrack.operations.orderscheduling.actions;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.orderscheduling.dao.OrderSchedulingDAO;
import com.scalar.chiptrack.operations.process.dao.NewProductDAO;
import com.scalar.chiptrack.sales.LineItem;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.NewSalesOrderDAO;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.forms.OrdersForm;
import com.scalar.chiptrack.users.User;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * @author Ravikanth
**/
public class OrderScheduleAction extends ChipTrackAction 
{
	private static final String ACTION_NAME = "/scheduling.do" ;
	public static final int CONSTANT_TIME_FOR_MANUAL_TRANSACTIONS = 5;
	
	public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception 
	{
		HttpSession session = request.getSession();
		HashMap errors 		= new HashMap();
		HashMap info 	 	= new LinkedHashMap();
		User user = (User) session.getAttribute ( SessionKeys.USER_KEY );
		String action = request.getParameter( "action" );

        if ( user == null )
        {
            if( ("reschedule".equals ( action ) ) || ("saveScheduleDate".equals ( action ) ) || ("releaseLots".equals ( action ) ) )
            {
                request.setAttribute ( "closeWindowAfterSessionExp", "true" );
			    return ( mapping.findForward( "showInventory" ) );
            }
            else{
                session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString () );
                return ( mapping.findForward ( "login" ) );
            }
        }

		OrdersForm ordersForm = (OrdersForm) form;

		String returnVal = "success";
		
		if( action == null )
		{
			request.setAttribute( "showList", "FALSE" );
		}
	
		if( "SearchOrders".equals( action ) )
		{
			String customerId 		= ordersForm.getCustomerId()+"";
			String mfgPartNo 		= ordersForm.getManufacturingPartNo();
			String salesOrderNo 	= ordersForm.getSalesOrderNo();
			String booking_year 	= ordersForm.getYear();
			ArrayList lineItemList  = null;
			
			if ( customerId != null )
			{
				customerId = customerId.trim ();
			}
			if ( mfgPartNo != null )
			{
				mfgPartNo = mfgPartNo.trim ();
			}
			if ( salesOrderNo != null )
			{
				salesOrderNo = salesOrderNo.trim ();
			}

			if(booking_year != null)
			{
				booking_year = booking_year.trim ();
			}
		
			try
			{
				lineItemList = SalesDAO.loadOrdersForScheduling ( customerId, mfgPartNo, salesOrderNo, booking_year );
	
				if( lineItemList.size() == 0 )
				{
					errors.put( ERROR_SALES_ORDERS_NOT_FOUND_ORDER_SCHEDULING, null );
				}
				else
				{
					//NewSalesOrderDAO.loadCustomerPartNumbersForSearch( null,lineItemList );
                    request.setAttribute( "showList", "TRUE" );
				}
			}
			catch( Exception e )
			{
				e.printStackTrace();
				errors.put( "Orders could not be loaded for Scheduling " , null );
			}
			
			request.setAttribute( "lineItemList", lineItemList );
			request.setAttribute( "scheduling", ordersForm );
			returnVal = "success";
		}
		else if ( "showLotDetail".equalsIgnoreCase( action ) )
		{
			String mfgPartNumber = request.getParameter( "mfgPartNo" );
			String fromDate 	 = request.getParameter( "fromDate" );
			String toDate		 = request.getParameter( "toDate" );
			ArrayList lotDetails = OrderSchedulingDAO.getLotDetails( mfgPartNumber, fromDate, toDate );
			request.setAttribute( "lotDetails", lotDetails );
			if( lotDetails == null || lotDetails.size() == 0 )
			{
				info.put( "Could not fetch the Lot Details for this Product Please contact System Administrator", "" );
			}
			returnVal = "showLots";
		}
		else if ( "showLineItemDetail".equalsIgnoreCase( action ) )
		{
			String mfgPartNumber 	= request.getParameter( "mfgPartNo" );
			String fromDate 		= request.getParameter( "fromDate" );
			String toDate			= request.getParameter( "toDate" );	
			ArrayList lineItemList 	= OrderSchedulingDAO.getBackLogDetails( mfgPartNumber, fromDate, toDate );
			request.setAttribute( "lineItemDetails", lineItemList );

			if( lineItemList == null || lineItemList.size() == 0 )
			{
				info.put( "Could not fetch the Back Log Details for this Product Please contact System Administrator", "" );
			}
			
			returnVal = "showLineItems";
		}
		else if ( "reschedule".equalsIgnoreCase( action ) ) 
		{
			try 
			{
				String mfgPartNumber 	= request.getParameter( "mfgPartNo" );
				String lineItemNumber 	= request.getParameter( "lineItemNo" );
				String salesOrderId 	= request.getParameter( "salesOrderId" );
				String requestedScheduleDate = request.getParameter( "requestedDate" );
				int requestedQty 		= Integer.parseInt ( request.getParameter( "quantity" ) );

				LineItem lineItem = OrderSchedulingDAO.scheduleLineItem ( lineItemNumber, salesOrderId, mfgPartNumber, requestedScheduleDate, requestedQty, (LinkedHashMap) info );
				request.setAttribute( "scheduleUnits", OrderSchedulingDAO.loadAllScheduleUnits( mfgPartNumber ) );
				request.setAttribute( "inventroryDetails", OrderSchedulingDAO.loadInventory( mfgPartNumber ) );
				
				session.setAttribute ( "lineItem", lineItem );
			}
			catch (ScalarException se)
			{
				errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_RESCHEDULING_SALES_ORDER );
				errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
				session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, " Error:Could not get re-schedule the LineItem " );
				session.setAttribute( SessionKeys.ERROR_REPORT, se );
			}
			returnVal = "showInventory";
		}
		else if ( "saveScheduleDate".equalsIgnoreCase ( action ) ) 
		{
			try 
			{
				String mfgPartNumber 	= request.getParameter( "mfgPartNo" );
				String scheduleDate 	= request.getParameter( "scheduleDate" );
				LineItem lineItem 		= (LineItem) session.getAttribute ( "lineItem" );
				lineItem.setScheduleDate( scheduleDate );

                LineItem oldLineItem = NewSalesOrderDAO.getLineItem( null,lineItem.getLineItemNo(), lineItem.getSalesOrderId());
				OrderSchedulingDAO.saveSchedulelineItem( lineItem, (LinkedHashMap) info );

                String oldScheduleDate;
                StringBuffer actionsTakenSummary = new StringBuffer();
                if ( oldLineItem.getRevisedDate() != null && !"".equals( oldLineItem.getRevisedDate() ) ) //Revised date is updated
                {
                    oldScheduleDate =  oldLineItem.getRevisedDate();
                    actionsTakenSummary.append("<br>Revised Ship Date ");
                }
                else //Scheduled date is updated
                {
                    oldScheduleDate =  oldLineItem.getScheduleDate() == null ? "" : oldLineItem.getScheduleDate();
                    actionsTakenSummary.append("<br>Schedule Date ");
                }
                if( scheduleDate == null )
                {
                    scheduleDate = "";
                }
                if(!scheduleDate.equals(oldScheduleDate))
                {
                    if("".equals(oldScheduleDate)) {
                        actionsTakenSummary.append( scheduleDate + " entered for Line item " + lineItem.getLineItemNo() );
                    }
                    else if ( "".equals( scheduleDate ) )
                    {
                        actionsTakenSummary.append("is removed for Line item " + lineItem.getLineItemNo() );
                    }
                    else
                    {
                        actionsTakenSummary.append( oldScheduleDate +" is changed to  "+ scheduleDate +"  for Line item " + lineItem.getLineItemNo() ) ;
                    }
                    try
                    {
                        SalesDAO.updateSalesAuditTrail ( null, lineItem.getSalesOrderId(), user.getUserId (), actionsTakenSummary.toString(), "" );
                    }
                    catch ( ScalarException e )
                    {
                        errors.put ( "Could not update Sales Audit Trail", null );
                    }
                }

				request.setAttribute( "scheduleUnits", OrderSchedulingDAO.loadAllScheduleUnits( mfgPartNumber ) );
				request.setAttribute( "inventroryDetails", OrderSchedulingDAO.loadInventory( mfgPartNumber ) );
			}
			catch ( ScalarException se ) 
			{
				//errors = new HashMap();
				errors.put ( "Internal Server Error", "Could not update Schedule Date" );
				se.printStackTrace();
			}
			returnVal = "showInventory";
		}
		else if( "releaseLots".equalsIgnoreCase( action ) )
		{
			try
			{
				String mfgPartNumber 	= request.getParameter( "mfgPartNo" );
				LineItem lineItem 		= (LineItem) session.getAttribute ( "lineItem" );
				
				lineItem.setSuggScheduleDate( null );
				lineItem.setScheduleDate( null );
				OrderSchedulingDAO.releaseSchedulelineItem( lineItem );
                try
                {
                    String actionsTakenSummary = "<br>Schedule Date(s) is removed for Line item " + lineItem.getLineItemNo();
                    SalesDAO.updateSalesAuditTrail ( null, lineItem.getSalesOrderId(), user.getUserId (), actionsTakenSummary, "" );
                }
                catch ( ScalarException e )
                {
                    errors.put ( "Could not update Sales Audit Trail", null );
                }
				request.setAttribute( "scheduleUnits", OrderSchedulingDAO.loadAllScheduleUnits( mfgPartNumber ) );
				request.setAttribute( "inventroryDetails", OrderSchedulingDAO.loadInventory( mfgPartNumber ) );
				info.put( "Reserved quantity for the Line Item is released", null );
			}
			catch( Exception e )
			{
				e.printStackTrace();
				//errors = new HashMap();
				errors.put ( "Internal Server Error", "Could not update Schedule Date" );
			}
			returnVal = "showInventory";
		}
		else if( "ShowInventory".equalsIgnoreCase( action ) ) 
		{
			try
			{
				String mfgPartNumber 	= request.getParameter( "mfgPartNo" );
				String lineItemNumber 	= request.getParameter( "lineItemNo" );
				String salesOrderId 	= request.getParameter( "salesOrderId" );

				LineItem lineItem = OrderSchedulingDAO.loadLineItem( mfgPartNumber, lineItemNumber, salesOrderId );
				session.setAttribute( "lineItem", lineItem );
				request.setAttribute( "scheduleUnits", OrderSchedulingDAO.loadAllScheduleUnits( mfgPartNumber ) );
				request.setAttribute( "inventroryDetails", OrderSchedulingDAO.loadInventory( mfgPartNumber ) );
				returnVal = "showInventory";
			}
			catch( Exception e )
			{
				e.printStackTrace();
				//errors = new HashMap();
				errors.put ( "Internal Server Error", "Could not Load the Line item Details" );
			}
		}
        if( action == null || "SearchOrders".equals( action ) || "ApproveOrder".equals(action) )
		{
			session.setAttribute( "customerList", CustomerDAO.getAllCustomerNames() );
            session.setAttribute( "productList", NewProductDAO.loadPartNumbers(null, 0, Constants.LOCATION_TYPE_FG, true, true, false, 0 ));
			session.setAttribute( "years", SalesOrderDAO.getYearList () );
		}
		
		request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
		request.setAttribute( SessionKeys.INFO_MESSAGES, info );

		return mapping.findForward( returnVal );
	}
}